﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using AutoUpdaterDotNET;
using System.Threading;

namespace ClientRun
{
    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            AutoUpdater.CheckForUpdateEvent += AutoUpdaterOnCheckForUpdateEvent;
        }

        public string AutoUpdaterUrl = "https://gitee.com/roby/ClientAutoUpdater/raw/master/ClientRun/ClientRun/AutoUpdaterTest.xml";
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            AutoUpdater.Start(AutoUpdaterUrl);
            button1.Enabled = true;
        }
        private void AutoUpdaterOnCheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args != null)
            {
                if (args.IsUpdateAvailable)
                {
                    try
                    {
                        DialogResult dialogResult;
                        if (args.Mandatory)
                        {
                            dialogResult =
                                MessageBox.Show(
                                    $@"这里有新的版本 {args.CurrentVersion} 可用.你可以使用 {args.InstalledVersion}. 这些需要更新. 点击OK进行更新.", @"可用更新",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                        }
                        else
                        {
                            dialogResult =
                                MessageBox.Show(
                                    $@"这里有新的版本 {args.CurrentVersion} 可用.你所处的版本 {
                                            args.InstalledVersion
                                        }. 你现在想更新客户端吗?", @"可用更新可用更新",
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information);
                        }
                        if (dialogResult.Equals(DialogResult.Yes) || dialogResult.Equals(DialogResult.OK))
                        {
                            try
                            {
                                if (AutoUpdater.DownloadUpdate())
                                {
                                    Application.Exit();
                                }
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message, exception.GetType().ToString(), MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        rtbLog.Text = "更新异常:" + ex.Message;
                    }
                }
                else
                {
                    MessageBox.Show(@"当前没有更新的版本,请晚点再重试.", @"没有可更新的.",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show(
                        @"更新出了点问题，网络无法到达更新服务器，请检查网络后进行重试.",
                        @"更新出错！", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private System.Timers.Timer timerUpdater;
        private void cbAutoUpdater_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAutoUpdater.Checked)
            {
                timerUpdater=new System.Timers.Timer
                {
                    Interval = 30 * 1000,
                    SynchronizingObject = this
                };
                timerUpdater.Elapsed += delegate
                {
                    AutoUpdater.Start(AutoUpdaterUrl);
                };
                timerUpdater.Start();
            }
            else
            {
                timerUpdater.Stop();
                timerUpdater = null;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            GetAutoUpdaterTest();
            button2.Enabled = true;
        }

        private void GetAutoUpdaterTest()
        {
            HttpWebResponse response;
            string responseText;

            if (Request_gitee_com(out response))
            {
                responseText = ReadResponse(response);
                rtbLog.BeginInvoke(new MethodInvoker(() =>
                {
                    rtbLog.Text = responseText;
                }));
                response.Close();
            }
            else
            {
                rtbLog.BeginInvoke(new MethodInvoker(() =>
                {
                    rtbLog.Text = "获取数据异常！";
                }));
            }
        }

        private static string ReadResponse(HttpWebResponse response)
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                Stream streamToRead = responseStream;
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    streamToRead = new GZipStream(streamToRead, CompressionMode.Decompress);
                }
                else if (response.ContentEncoding.ToLower().Contains("deflate"))
                {
                    streamToRead = new DeflateStream(streamToRead, CompressionMode.Decompress);
                }

                using (StreamReader streamReader = new StreamReader(streamToRead, Encoding.UTF8))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        private bool Request_gitee_com(out HttpWebResponse response)
        {
            response = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AutoUpdaterUrl);

                request.Timeout = 5 * 1000;
                //request.KeepAlive = true;
                //request.Headers.Add("Upgrade-Insecure-Requests", @"1");
                //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36";
                //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                //request.Headers.Add("Sec-Fetch-Site", @"none");
                //request.Headers.Add("Sec-Fetch-Mode", @"navigate");
                //request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
                //request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh,zh-CN;q=0.9,en;q=0.8,zh-TW;q=0.7");

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
                else return false;
            }
            catch (Exception)
            {
                if (response != null) response.Close();
                return false;
            }

            return true;
        }
    }
}
